module CorsHelpers
  extend Grape::API::Helpers

  module ClassMethods
    def cors(url, origins: [], methods: [], headers: [], credential: true)
      options url do
        origins = [origins] unless origins.is_a? Array
        request_origin = request.headers['Origin']
        error!('Origin not allowed', 403) unless origins.include?('*') || origins.include?(request_origin)

        header 'Access-Control-Allow-Origin', request_origin
        header 'Access-Control-Allow-Methods', methods.map{|m| m.to_s.upcase}.join(', ')
        header 'Access-Control-Allow-Headers', headers.map{|m| m.to_s.upcase}.join(', ')
        header 'Access-Control-Allow-Credential', credential.to_s
        body false
      end
    end
  end
end